import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Md5 } from 'ts-md5';
import { Router, ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-profile',
  templateUrl: './personal-center.component.html',
  styleUrls: ['./personal-center.component.css']
})
export class PersonalCenterComponent implements OnInit {
  username: string;
  user: any; // 用户信息对象
  isEditing: boolean = false;
  isEmpty: boolean = false;
  visitedRooms: any[]; // 已访问房间列表
  public token: any;
  //router: any;

  constructor(private http: HttpClient, private router: Router, private route: ActivatedRoute) {
    this.username = sessionStorage.getItem('username') || '';
    this.user = {};
    this.isEditing = false;
    this.visitedRooms = [];
  }


  ngOnInit(): void {
    // 初始化用户信息
    //this.getUserInfo();
    // 初始化已访问房间列表
    const username = sessionStorage.getItem('username') || '';
    this.getVisitedRooms(username);

  }

  getVisitedRooms(username: string): void {
    //JWT
    this.token = sessionStorage.getItem('token');
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'token': this.token })
    };
    // 请求已访问房间列表
    this.http.get<any>(`http://124.221.112.204:3389/user/visited-rooms?username=${username}`, httpOptions).subscribe(
      response => {
        if (response.code === 200 && response.data) {
          this.visitedRooms = response.data;
          console.log(response);
        } else {
          // 处理错误或无数据情况
          window.alert('未找到房间信息');
          this.isEmpty = true;
        }
      },
      error => {
        // 处理错误
        window.alert('未找到房间信息');
      }
    );
  }


  editProfile(): void {
    this.isEditing = true;
  }

  saveProfile(): void {
    //加密
    if (this.user.password != null && this.user.username != null) {
      this.user.password = Md5.hashStr(this.user.password);
      this.user.id = sessionStorage.getItem('userid');//以id标志原来的用户

      //JWT
      this.token = sessionStorage.getItem('token');
      const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json', 'token': this.token })
      };
      // 修改用户信息
      this.http.post('http://124.221.112.204:3389/user/updateInfo', this.user, httpOptions).subscribe(
        async (response: any) => {
          if (response.code === 200 && response.data) {
            this.isEditing = false;
            // 更新sessionStorage中的用户名和token
            sessionStorage.setItem('username', this.user.username);
            sessionStorage.setItem('token', response.data.token);
            console.log(response);
            this.getVisitedRooms(this.user.username);
            var f: any = document.getElementById('iframeId');
            // 触发子页面的监听事件
            f.contentWindow.postMessage({ username: this.user.username }, '*');
            window.alert('密码修改成功');
            this.user.username = '';
            this.user.password = '';
          }
        },
        error => {
          // 处理错误
          window.alert('保存失败');
        }
      );
    } else {
      window.alert('新用户名或密码不能为空');
    }
  }

  cancelEdit(): void {
    this.isEditing = false;
  }

  goBackToIndex() {
    this.router.navigateByUrl('index');
  }
}
